package com.lw.leetcode.node;

import java.util.*;

/**
 * 剑指 Offer 32 - III. 从上到下打印二叉树 III
 *
 * @Author liw
 * @Date 2021/5/13 13:41
 * @Version 1.0
 */
public class LevelOrder {

    public List<List<Integer>> levelOrder(TreeNode root) {
        Stack<TreeNode> a = new Stack<>();
        Stack<TreeNode> b = new Stack<>();
        List<List<Integer>> all =  new ArrayList<>();
        if (root == null) {
            return all;
        }
        b.add(root);
        boolean flag = false;
        while (!a.isEmpty() || !b.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            if (flag) {
                while (!a.isEmpty()) {
                    TreeNode pop = a.pop();
                    if (pop.left != null) {
                        b.add(pop.left);
                    }
                    if (pop.right != null) {
                        b.add(pop.right);
                    }
                    list.add(pop.val);
                }
                all.add(list);
                flag = false;
            }else {
                while (!b.isEmpty()) {
                    TreeNode pop = b.pop();
                    if (pop.right != null) {
                        a.add(pop.right);
                    }
                    if (pop.left != null) {
                        a.add(pop.left);
                    }
                    list.add(pop.val);
                }
                all.add(list);
                flag = true;
            }
        }
        return all;
    }

}
